package app.controllers;

import app.Const;
import app.constant.MemberConstant;
import app.jobs.InviteMemberJob;
import app.kit.CommonKit;
import app.kit.SmsCodeKit;
import app.kit.SmsKit;
import app.models.basic.Notes;
import app.models.member.Account;
import app.models.member.Member;
import app.services.SerialService;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import goja.StringPool;
import goja.mvc.Controller;
import goja.mvc.render.CaptchaRender;
import goja.security.goja.SecurityKit;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;

import java.sql.SQLException;
import java.util.Map;

/**
 * <p>
 * The url register Controller.
 * 会员注册
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
public class RegisterController extends Controller {

    /**
     * The index route.
     * the url /register
     * the view in index.ftl
     */
    public void index() {
        String phone = getPara("phone");
        String notes = Notes.dao.findByRegister();
        if (CommonKit.isMoible(phone)) {
            setAttr("phone", phone);
        }
        setAttr("note", notes);

    }

    /**
     * 设置密码
     */
    public void password() {
        final String username = getPara("username", StringPool.EMPTY);
        final String phone = getPara("phone", StringPool.EMPTY);
        final String interPhone = getPara("rphone", StringPool.EMPTY);
        setAttr("phone", phone);
        setAttr("invite", interPhone);
        setAttr("username", username);
    }

    /**
     * 发送验证码
     */
    public void sendsms() {
        final String phone = getPara("phone");
        if (!Strings.isNullOrEmpty(phone)) {
            SmsKit.registered(phone);
        }
        renderAjaxSuccess();
    }

    //验证手机号是否已经注册
    public void regphone() {
        String phone = getPara("phone");
        if (!Strings.isNullOrEmpty(phone)) {
            Member member = Member.dao.findbyPhone(phone);
            Map<String, String> result = Maps.newHashMap();
            if (member == null) {
                result.put("ok", null);
                renderJson(result);
            } else {
                result.put("error", "该手机号已被注册,请更换!");
                renderJson(result);
            }
        } else{
            renderJson();
        }
    }

    //验证手机号是否存在
    public void hadphone() {
        String phone = getPara("phone");
        if (!Strings.isNullOrEmpty(phone)) {
            Member member = Member.dao.findbyPhone(phone);
            Map<String, String> result = Maps.newHashMap();
            if (member == null) {
                result.put("error", "该推荐手机号不存在!");
                renderJson(result);
            } else {
                result.put("ok", null);
                renderJson(result);
            }
        }
    }


    /*
    验证码验证
     */
    public void checkedMcode() {
        String captcha = getPara("captcha");
        final boolean validate = CaptchaRender.validate(this, captcha);
        Map<String, String> result = Maps.newHashMap();
        if (!validate) {
            result.put("error", "请输入正确的验证码!");
            renderJson(result);
        } else {
            result.put("ok", null);
            renderJson(result);
        }
    }

    public void checkname() {
        String username = getPara("name");
        if (!Strings.isNullOrEmpty(username)) {
            Member member = Member.dao.findByUsername(username);
            Map<String, String> result = Maps.newHashMap();
            if (member == null) {
                result.put("ok", null);
            } else {
                result.put("error", "用户名已被其他用户使用了，请更换!");
            }
            renderJson(result);
        } else {
            renderNull();
        }
    }



    @Before(POST.class)
    public void save() {
        String username = getPara("username");
        String plant_pwd = getPara("plant_pwd");
        String captcha = getPara("codes");
        String phone = getPara("phone");
        String invite_mobile = getPara("invite_mobile");
        String rpassword = getPara("rpassword");
        //验证输入信息
        if (Strings.isNullOrEmpty(username) ||Strings.isNullOrEmpty(phone) || Strings.isNullOrEmpty(captcha) || Strings.isNullOrEmpty(plant_pwd) || Strings.isNullOrEmpty(rpassword)) {
            renderAjaxFailure("输入的信息不能为空！");
            return;
        }
        if (!SmsCodeKit.checkRegisted(phone, captcha)) {
            renderAjaxFailure("您输入的验证码不正确");
            return;
        }
        if (!CommonKit.isMoible(phone)) {
            renderAjaxFailure("请输入正确的手机号码");
            return;
        }
        if (!Strings.isNullOrEmpty(invite_mobile) && !CommonKit.isMoible(invite_mobile)) {
            renderAjaxFailure("请输入正确的手机号码");
            return;
        }
        if (plant_pwd.length() < 6) {
            renderAjaxFailure("密码长度6~16个字符");
            return;
        }
        if (!rpassword.equals(plant_pwd)) {
            renderAjaxFailure("两次输入的密码不一致");
            return;
        }
        if (StringUtils.equals(invite_mobile, phone)) {
            renderAjaxFailure("邀请人手机号码不能与注册号码一致");
            return;
        }
        Member phone_member = Member.dao.findbyPhone(phone);
        if (phone_member != null) {
            renderAjaxFailure("手机号码已经被注册，请更换。");
            return;
        }
        final Member member = new Member();
        member.set("phone", phone);
        member.set("nick_name", username);
        member.set("gender", MemberConstant.GENDER.UNKNOW);
        member.set("avatar", StringPool.EMPTY);
        member.set("invitemobile", invite_mobile);
        final DateTime now = DateTime.now();
        member.set(Const.FIELD_CREATE_TIME, now);
        member.set("regiest_time", now);
        member.set(Const.FIELD_CODE, SerialService.memberCode());
        member.set(Const.FIELD_STATUS, MemberConstant.NORMAL);
        member.generatePassword(plant_pwd);

        final Account account = new Account();
        boolean ok = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                if (member.save()) {
                    account.set(Const.FIELD_MEMBER, member.getNumber(StringPool.PK_COLUMN).intValue());
                    return account.save();
                }
                return false;
            }
        });
        if (ok) {
            // 注册成功，需要清除注册码信息
            SmsCodeKit.clearRegisted(phone);
            final int memberId = member.getNumber(StringPool.PK_COLUMN).intValue();
            // 返回信息中不带这两个
            member.remove(Member.FIELD_SALT);
            member.remove(Member.FIELD_PASSWORD);
            if(!Strings.isNullOrEmpty(invite_mobile)) {
                new InviteMemberJob(phone, invite_mobile, memberId, DateTime.now()).now();
            }
            Member member1 = Member.dao.findbyPhone(phone);
            SecurityKit.login(member1, plant_pwd, false, getRequest(), getResponse());
            renderAjaxSuccess();
        } else {
            renderAjaxError("注册失败");
        }
    }



    public void complete() {

    }
}